package com.jiang.mybatis.service;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiang.feign.mybatis_plus.GoodsService;
import com.jiang.feign.mybatis_plus.dto.GoodsDTO;
import com.jiang.mybatis.entity.User;
import com.jiang.mybatis.mapper.UserMapper;
import com.jiang.mybatis.view.dto.UserDTO;
import com.jiang.mybatis.view.dto.UserSearchDTO;
import com.jiang.mybatis.view.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author jiang
 * @since 2022-10-27
 */
@Service
public class UserService {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserMapper userMapper;

    public void add(UserDTO DTO) {
        User user = new User();
        BeanUtil.copyProperties(DTO, user);
        userMapper.insert(user);

        // 调用服务新增
        GoodsDTO goodsDTO = new GoodsDTO();
        goodsDTO.setName("iphone");
        goodsDTO.setPrice(10);
        goodsDTO.setQuantity(100);
        goodsService.add(goodsDTO);
    }

    public void del(Long id) {
        userMapper.deleteById(id);
    }

    public void update(Long id, UserDTO DTO) {
        User user = userMapper.selectById(id);
        BeanUtils.copyProperties(DTO, user);
        userMapper.updateById(user);
    }

    public UserVO getById(Long id) {
        User user = userMapper.selectById(id);
        if(user == null) return null;
        UserVO vo = new UserVO();
        BeanUtil.copyProperties(user, vo);
        return vo;
    }

    public com.jiang.core.common.PageHelper<UserVO> page(UserSearchDTO DTO) {
        PageHelper.startPage(Integer.parseInt(DTO.getCurrentPage()+""), Integer.parseInt(DTO.getPageSize()+""));
        List<User> list = userMapper.page(DTO);
        PageInfo<User> page = new PageInfo<>(list);

        List<User> records = page.getList();
        List<UserVO> vos = BeanUtil.copyToList(records, UserVO.class);
        return new com.jiang.core.common.PageHelper<>(page.getPageNum(), page.getPageSize(), page.getTotal(), vos);
    }
}
